//
//  WXBindingViewController.m
//  Btpin
//
//  Created by Vic on 2019/6/6.
//  Copyright © 2019 Vic. All rights reserved.
//

#import "WXBindingViewController.h"
#import "GeneralWebViewViewController.h"
#import "AESEnrypt.h"
#import "NSString+AES.h"
#import "AppDelegate.h"
#import "IDSelectViewController.h"
#import "CompanyFirstInfoViewController.h"
#import "CompanySecondInfoViewController.h"
#import "CompanyInfoViewController.h"
#import "PersonalFirstInfoViewController.h"
#import "PersonalEducationInfoViewController.h"
#import "PersonalWorkExperienceViewController.h"
#import "CountryCodeViewController.h"

@interface WXBindingViewController ()<UITextFieldDelegate>
{
    UILabel *topLbl;
//    UIButton *countryCodeBtn;
    UITextField *phoneTextField;
    UITextField *captchaTextField;
    UITextField *passwordTextField;
    
    UIButton *okBtn;
    UIButton *changeBtn;
    
    UIButton *captchaButton;
    NSInteger timerInt;
    
    BOOL newOrOldAccountFlag; // YES：新账号 NO：老账号
    NSDictionary *responseObjectDic;
    
    NSString *countryCodeStr;
}
@property (nonatomic, strong) NSTimer *timer;
@end

@implementation WXBindingViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    
//    countryCodeStr = @"86";
    countryCodeStr = @"";
    newOrOldAccountFlag = YES;
    timerInt = CaptchaTime;
    [self initUI];
}
- (void)countryCodeBtnTap {
    CountryCodeViewController *CCVC = [[CountryCodeViewController alloc] init];
    CCVC.selectCode = ^(NSString * _Nonnull code) {
        self->countryCodeStr = code;
//        [self->countryCodeBtn setTitle:[NSString stringWithFormat:@"+ %@", code] forState:UIControlStateNormal];
    };
    [self.navigationController pushViewController:CCVC animated:YES];
}
- (void)initUI {
    if([DataToolsControl sharedManager].isApple){
        self.navigationItem.title = @"苹果ID登录";
    }else{
        self.navigationItem.title = @"微信登录";
    }
//    topLbl = [UIToolsControl initLabelWithFrame:CGRectMake(30*Scale, 15*Scale, 200, 50*Scale) text:((self.wxBindingVCType == WXBindingVCTypeOfNewAccount)?@"绑定新账号":@"绑定已有账号") textColor:THEMECOLOR_OF_TEXT_333333 font:Font_23];
    topLbl = [UIToolsControl initLabelWithFrame:CGRectMake(30*Scale, 15*Scale, 200, 50*Scale) text:@"绑定新账号" textColor:THEMECOLOR_OF_TEXT_333333 font:Font_23];
    [self.view addSubview:topLbl];
    
//    countryCodeBtn = [UIToolsControl initButtonWithFrame:CGRectMake(ScalePS(20), EndY(topLbl), ScalePS(50), ScalePS(50)) imageName:nil target:self action:@selector(countryCodeBtnTap) title:[NSString stringWithFormat:@"+ %@", countryCodeStr] titleColor:THEMECOLOR_OF_TEXT_333333];
//    countryCodeBtn.titleLabel.font = Font(Font_15);
//    countryCodeBtn.titleLabel.adjustsFontSizeToFitWidth = YES;
//    countryCodeBtn.contentHorizontalAlignment = UIControlContentHorizontalAlignmentRight;
//    [self.view addSubview:countryCodeBtn];
    
//    phoneTextField = [UIToolsControl initTextFieldWithFrame:CGRectMake(EndX(countryCodeBtn)+10*Scale, EndY(topLbl), WIDTH-60*Scale-ScalePS(50), 50*Scale) placeholder:PhoneNumberPlaceholderText secureTextEntry:NO font:Font_17 padding:YES];
    phoneTextField = [UIToolsControl initTextFieldWithFrame:CGRectMake(30*Scale, EndY(topLbl), WIDTH-60*Scale, 50*Scale) placeholder:PhoneNumberPlaceholderText secureTextEntry:NO font:Font_17 padding:YES];
    [phoneTextField borderColor:THEMECOLOR_OF_TEXT_cccccc borderWidth:lineH borderType:BorderSideTypeBottom];
    phoneTextField.delegate = self;
    phoneTextField.keyboardType = UIKeyboardTypeNumberPad;
    [self.view addSubview:phoneTextField];
    
    captchaTextField = [UIToolsControl initTextFieldWithFrame:CGRectMake(30*Scale, EndY(phoneTextField)+25*Scale, WIDTH-150*Scale, 50*Scale) placeholder:CaptchaPlaceholderText secureTextEntry:NO font:Font_17 padding:YES];
    captchaTextField.delegate = self;
    captchaTextField.keyboardType = UIKeyboardTypeNumberPad;
    [self.view addSubview:captchaTextField];
    UIView *lineView = [UIToolsControl initViewWithFrame:CGRectMake(30*Scale, EndY(captchaTextField)-1, WIDTH-60*Scale, lineH) backgroundColor:THEMECOLOR_OF_TEXT_cccccc];
    [self.view addSubview:lineView];
    captchaButton = [UIToolsControl initButtonWithFrame:CGRectMake(WIDTH-120*Scale, EndY(phoneTextField)+30*Scale, 100*Scale, 40*Scale) imageName:nil target:self action:@selector(sendCaptchaBtnTap) title:@"发送验证码" titleColor:THEMECOLOR_OF_TEXT_333333];
    captchaButton.titleLabel.font = Font(Font_14);
    [self.view addSubview:captchaButton];
    
    passwordTextField = [UIToolsControl initTextFieldWithFrame:CGRectMake(30*Scale, EndY(captchaButton)+25*Scale, WIDTH-60*Scale, 50*Scale) placeholder:PasswordSetPlaceholderText secureTextEntry:YES font:Font_17 padding:YES];
    [passwordTextField borderColor:THEMECOLOR_OF_TEXT_cccccc borderWidth:lineH borderType:BorderSideTypeBottom];
    passwordTextField.delegate = self;
    passwordTextField.keyboardType = UIKeyboardTypeNamePhonePad;
    [self.view addSubview:passwordTextField];
    
    CGFloat okBtnStartY = EndY(passwordTextField)+70*Scale;
    okBtn = [UIToolsControl initButtonWithFrame:CGRectMake(40*Scale, okBtnStartY, WIDTH-80*Scale, 46*Scale) imageName:nil target:self action:@selector(okBtnTap) title:@"绑定" titleColor:COLOR_OF_WHITE];
    okBtn.titleLabel.font = FontBold(Font_17);
    okBtn.backgroundColor = THEMECOLOR_OF_ORANGE;
    okBtn.layer.cornerRadius = 23*Scale;
    okBtn.layer.masksToBounds = YES;
    [self.view addSubview:okBtn];
    
    changeBtn = [UIToolsControl initButtonWithFrame:CGRectMake(EndX(okBtn)-120*Scale, EndY(okBtn)+10*Scale, 120*Scale, 40*Scale) imageName:nil target:self action:@selector(changeBtnTap) title:@"绑定已有账号" titleColor:THEMECOLOR_OF_TEXT_333333];
    changeBtn.titleLabel.font = Font(Font_14);
    [self.view addSubview:changeBtn];
    
    
    NSString *clauseString = @"登录即代表您已同意我们的《服务协议》和《隐私政策》";
    CGFloat clauseStrWidth = [UIToolsControl textWidth:clauseString size:CGSizeMake(MAXFLOAT, 40*Scale) font:Font_13]+1;
    NSMutableAttributedString *attributedString = [[NSMutableAttributedString alloc] initWithString:clauseString];
    [attributedString addAttribute:NSFontAttributeName value:Font(Font_13) range:NSMakeRange(0, clauseString.length)];
    [attributedString addAttribute:NSForegroundColorAttributeName value:THEMECOLOR_OF_TEXT_666666 range:NSMakeRange(0, clauseString.length)];
    [attributedString addAttribute:NSForegroundColorAttributeName value:THEMECOLOR_OF_ORANGE range:NSMakeRange(12, 13)];
    [attributedString addAttribute:NSForegroundColorAttributeName value:THEMECOLOR_OF_TEXT_666666 range:NSMakeRange(18, 1)];
    UILabel *clauseLabel = [[UILabel alloc] initWithFrame:CGRectMake((WIDTH-clauseStrWidth)*0.5, HEIGHT-HeightOfStatusBarAndNavigationBar-SIMEmojKeyBoardkBottomNOSafeArea_Height-60*Scale, clauseStrWidth, 40*Scale)];
    clauseLabel.font = Font(Font_13);
    clauseLabel.backgroundColor = COLOR_OF_CLEAR;
    clauseLabel.attributedText = attributedString;
    clauseLabel.textAlignment = NSTextAlignmentCenter;
    [self.view addSubview:clauseLabel];
    [clauseLabel yb_addAttributeTapActionWithStrings:@[@"《服务协议》", @"《隐私政策》"] tapClicked:^(NSString *string, NSRange range, NSInteger index) {
        GeneralWebViewViewController *GWVC = [[GeneralWebViewViewController alloc] init];
        if ([string isEqualToString:@"《服务协议》"]) {
            NSLog(@"服务协议");
            GWVC.showType = GeneralWebViewTypeOfResignAgreement;
        } else {
            NSLog(@"隐私政策");
            GWVC.showType = GeneralWebViewTypeOfPrivacyPolicy;
        }
        GWVC.hidesBottomBarWhenPushed = YES;
        [self.navigationController pushViewController:GWVC animated:YES];
    }];
}
- (void)okBtnTap {
    [UIToolsControl resignFirstResponderForTextFieldArray:@[phoneTextField, passwordTextField, captchaTextField]];
    if (phoneTextField.text.length>0) {
        if ([UIToolsControl validatePhoneNumber:phoneTextField.text]) {
            if (captchaTextField.text.length>=0) {
                if (newOrOldAccountFlag) {
                    if (passwordTextField.text.length>=6) {
                        [self upDateForRegister];
                    } else {
                        SVPHUDError(PasswordAlertText);
                        [passwordTextField becomeFirstResponder];
                    }
                } else {
                    [self upDateForSigninByCaptcha];
                }
            } else {
                SVPHUDError(CaptchaAlertText);
                [captchaTextField becomeFirstResponder];
            }
        } else {
            SVPHUDError(PhoneNumberOKAlertText);
            [phoneTextField becomeFirstResponder];
        }
    } else {
        SVPHUDError(PhoneNumberAlertText);
        [phoneTextField becomeFirstResponder];
    }
}
- (void)upDateForRegister {
    SVPHUDShow;
    NSMutableDictionary *dic = [NSMutableDictionary dictionaryWithCapacity:0];
    dic = [UIToolsControl getPublicParameter];
    [dic setObject:phoneTextField.text forKey:@"mobile"];
    [dic setObject:captchaTextField.text forKey:@"verify_code"];
    [dic setObject:[passwordTextField.text aci_encryptWithAES] forKey:@"password"];
    [dic setObject:countryCodeStr forKey:@"country_code"];
    
    [BaseNetManager requestWithMethod:POST path:Register_URL params:dic successBlock:^(NSDictionary *responseObject) {
        if ([responseObject[@"code"] integerValue] == 2000) {
            [self upDateForSignin];

//            [self bindWXCode];
        } else {
            SVPHUDError(responseObject[@"msg"]);
        }
    } failurBlock:^(NSError *error) {
        SVPHUDError(NetErrorAlertText);
    }];
}
- (void)upDateForSignin {
    SVPHUDShow;
    NSMutableDictionary *dic = [NSMutableDictionary dictionaryWithCapacity:0];
    dic = [UIToolsControl getPublicParameter];
    [dic setObject:phoneTextField.text forKey:@"username"];
    [dic setObject:[passwordTextField.text aci_encryptWithAES] forKey:@"password"];
    
    [BaseNetManager requestWithMethod:POST path:Signin_Pwd_URL params:dic successBlock:^(NSDictionary *responseObject) {
        if ([responseObject[@"code"] integerValue] == 2000) {
            SVPHUDSuccess(responseObject[@"msg"]);
            
            [DataToolsControl sharedManager].isWXSigninToken = [UIToolsControl dataAnalysis:responseObject[@"data"][@"token"]];
            
            self->responseObjectDic = responseObject;
            [self bindWXCode];
        } else {
            NSString *str = [NSString stringWithFormat:@"%@", responseObject[@"msg"]];
            SVPHUDError(str);
        }
    } failurBlock:^(NSError *error) {
        SVPHUDError(NetErrorAlertText);
    }];
}
- (void)upDateForSigninByCaptcha {
    SVPHUDShow;
    NSMutableDictionary *dic = [NSMutableDictionary dictionaryWithCapacity:0];
    dic = [UIToolsControl getPublicParameter];
    [dic setObject:phoneTextField.text forKey:@"mobile"];
    [dic setObject:captchaTextField.text forKey:@"verify_code"];
    [dic setObject:countryCodeStr forKey:@"country_code"];
    
    [BaseNetManager requestWithMethod:POST path:Signin_SMSSignin_URL params:dic successBlock:^(NSDictionary *responseObject) {
        if ([responseObject[@"code"] integerValue] == 2000) {
            SVPHUDSuccess(responseObject[@"msg"]);
            
            [DataToolsControl sharedManager].isWXSigninToken = [UIToolsControl dataAnalysis:responseObject[@"data"][@"token"]];
            
            self->responseObjectDic = responseObject;
            [self bindWXCode];
        } else {
            NSString *str = [NSString stringWithFormat:@"%@", responseObject[@"msg"]];
            SVPHUDError(str);
        }
    } failurBlock:^(NSError *error) {
        SVPHUDError(NetErrorAlertText);
    }];
}
- (void)detailDataAndPushVC:(NSDictionary *)responseObject {
    [DataToolsControl dataAnalysisUserInfo:responseObject];
    
    UD_SetOForK(isYes, isSignin);
    UDSynchronize;
    
//       [DataToolsControl autoLoginForInitIM];
    [DataToolsControl initIMPeizhi];
    [AppDelegate loadLocationData];
    
    NSDictionary *data = responseObject[@"data"];
    if (data[@"user_guide"] && [data[@"user_guide"] length] && ([data[@"user_guide"] isEqualToString:@"choose_role"])) { // 用户还没选角色 （选择用户角色）
        IDSelectViewController *IDSVC = [[IDSelectViewController alloc] init];
        IDSVC.hidesBottomBarWhenPushed = YES;
        [self.navigationController pushViewController:IDSVC animated:NO];
    } else {
        if ([data[@"user_guide"] isEqualToString:@"company_add_job"]) { // 添加招聘职位
            [DataToolsControl getMyBaseInfoForCompany:^(BOOL requestFlag) {
                [SharedApp showViewController:TabBarTypeOfCompany];
                UITabBarController *tabBarController = (UITabBarController *)[UIApplication sharedApplication].keyWindow.rootViewController;
                tabBarController.selectedIndex = 1;
            }];
        } else if ([data[@"user_guide"] isEqualToString:@"company_create"]) { // 招聘者下面没有企业的话就会引导创建
            CompanyFirstInfoViewController *IDSVC = [[CompanyFirstInfoViewController alloc] init];
            IDSVC.isRegisterPush = YES;
            IDSVC.hidesBottomBarWhenPushed = YES;
            [self.navigationController pushViewController:IDSVC animated:NO];
        } else if ([data[@"user_guide"] isEqualToString:@"company_info"]) { // 填写企业信息
            CompanySecondInfoViewController *IDSVC = [[CompanySecondInfoViewController alloc] init];
            IDSVC.isRegisterPush = YES;
            IDSVC.hidesBottomBarWhenPushed = YES;
            [self.navigationController pushViewController:IDSVC animated:NO];
        } else if ([data[@"user_guide"] isEqualToString:@"company_audit"]) { // 企业未认证
            SVPHUDShow;
            [DataToolsControl getMyBaseInfoForCompany:^(BOOL requestFlag) {
                SVPHUDDismiss;
                [SharedApp showViewController:TabBarTypeOfCompany];
                UITabBarController *tabBarController = (UITabBarController *)[UIApplication sharedApplication].keyWindow.rootViewController;
                tabBarController.selectedIndex = tabBarController.viewControllers.count-1;
                RootNavigationController *navigationController = (RootNavigationController *)[UIApplication sharedApplication].keyWindow.rootViewController;
                
                CompanyInfoViewController *CIVC = [[CompanyInfoViewController alloc] init];
                CIVC.hidesBottomBarWhenPushed = YES;
                [navigationController pushViewController:CIVC animated:YES];
            }];
        } else if (([data[@"user_guide"] isEqualToString:@"resume_create"])) { // 创建简历页
            PersonalFirstInfoViewController *PFIVC = [[PersonalFirstInfoViewController alloc] init];
            PFIVC.isRegisterPush = YES;
            PFIVC.hidesBottomBarWhenPushed = YES;
            [self.navigationController pushViewController:PFIVC animated:NO];
        } else if ([data[@"user_guide"] isEqualToString:@"resume_edu"]) { // 完善简历中教育经历
            if (data[@"is_graduate"] && ([data[@"is_graduate"] integerValue] == 0)) {
                [DataToolsControl sharedManager].idType = IDTypeOfWorker;
            } else {
                [DataToolsControl sharedManager].idType = IDTypeOfFreshGraduate;
            }
            
            PersonalEducationInfoViewController *PMRVC = [[PersonalEducationInfoViewController alloc] init];
            PMRVC.isRegisterPush = YES;
            PMRVC.hidesBottomBarWhenPushed = YES;
            [self.navigationController pushViewController:PMRVC animated:NO];
        } else if ([data[@"user_guide"] isEqualToString:@"resume_work"]) { // 完善简历中工作经历
            PersonalWorkExperienceViewController *PWEVC = [[PersonalWorkExperienceViewController alloc] init];
            PWEVC.isRegisterPush = YES;
            PWEVC.hidesBottomBarWhenPushed = YES;
            [self.navigationController pushViewController:PWEVC animated:NO];
        } else {
            if ([data[@"user_role"] integerValue] == 1) {
                [DataToolsControl getMyBaseInfoForCompany:^(BOOL requestFlag) {
                    [SharedApp showViewController:TabBarTypeOfCompany];
                }];
            } else {
                [DataToolsControl getMyBaseInfoForWorker:^(BOOL requestFlag) {
                    [SharedApp showViewController:TabBarTypeOfPersonal];
                }];
            }
        }
    }
}
- (void)changeBtnTap {
    newOrOldAccountFlag = !newOrOldAccountFlag;
    captchaTextField.text = nil;
    timerInt = 1;
    [self timerClick];
    
    topLbl.text = ((newOrOldAccountFlag)?@"绑定新账号":@"绑定已有账号");
    
    passwordTextField.hidden = !newOrOldAccountFlag;
    CGFloat okBtnStartY = ((newOrOldAccountFlag?EndY(passwordTextField):EndY(captchaButton)))+70*Scale;
    okBtn.frame = CGRectMake(40*Scale, okBtnStartY, WIDTH-80*Scale, 46*Scale);
    changeBtn.frame = CGRectMake(EndX(okBtn)-120*Scale, EndY(okBtn)+10*Scale, 120*Scale, 40*Scale);
    [changeBtn setTitle:((newOrOldAccountFlag)?@"绑定已有账号":@"绑定新账号") forState:UIControlStateNormal];
}
- (void)sendCaptchaBtnTap {
    NSLog(@"sendCaptchaBtnTap");
    if (phoneTextField.text.length>0) {
        if ([UIToolsControl validatePhoneNumber:phoneTextField.text]) {
            SVPHUDShow;
            __weak __typeof(self)weakSelf = self;
            [UIToolsControl getCaptcha:phoneTextField.text countryCode:countryCodeStr type:[UIToolsControl getCaptchaType:(newOrOldAccountFlag?GetCaptchaTypeOfRegister:GetCaptchaTypeOfSignin)] successBlock:^(id response) {
                __strong __typeof(weakSelf)strongSelf = weakSelf;
                if ([response[@"code"] integerValue] == 2000) {
                    SVPHUDSuccess(response[@"msg"]);
                    [self->captchaTextField becomeFirstResponder];
                    strongSelf.timer = [NSTimer scheduledTimerWithTimeInterval:1.0 target:self selector:@selector(timerClick) userInfo:nil repeats:YES];
                } else {
                    SVPHUDError(response[@"msg"]);
                }
            }];
        } else {
            SVPHUDError(PhoneNumberOKAlertText);
        }
    } else {
        SVPHUDError(PhoneNumberAlertText);
        [phoneTextField becomeFirstResponder];
    }
}
- (void)timerClick {
    timerInt--;
    if (timerInt>0) {
        [captchaButton setTitleColor:THEMECOLOR_OF_TEXT_cccccc forState:UIControlStateNormal];
        [captchaButton setTitle:[NSString stringWithFormat:@"%ldS", (long)timerInt] forState:UIControlStateNormal];
        captchaButton.userInteractionEnabled = NO;
    } else {
        [captchaButton setTitle:GetCaptchaText forState:UIControlStateNormal];
        [captchaButton setTitleColor:THEMECOLOR_OF_TEXT_333333 forState:UIControlStateNormal];
        captchaButton.userInteractionEnabled = YES;
        timerInt = CaptchaTime;
        [self.timer invalidate];
        self.timer = nil;
    }
}
- (void)bindWXCode {
    SVPHUDShow;
    NSMutableDictionary *dic = [NSMutableDictionary dictionaryWithCapacity:0];
    dic = [UIToolsControl getPublicParameter];
    if([DataToolsControl sharedManager].isApple){
        [dic setObject:@"apple" forKey:@"type"];
    }else{
        [dic setObject:@"weixin" forKey:@"type"];
    }
    [dic setObject:[DataToolsControl sharedManager].isWXSigninCode forKey:@"code"];
    [dic setObject:[DataToolsControl sharedManager].isWXSigninToken forKey:@"token"];
    
    [BaseNetManager requestWithMethod:POST path:User_Bind_OpenSignin_URL params:dic successBlock:^(NSDictionary *responseObject) {
        if ([responseObject[@"code"] integerValue] == 2000) {
            SVPHUDSuccess(responseObject[@"msg"]);
            UD_SetOForK(isYes, isWXSigninBind);
            UDSynchronize;
//            [DataToolsControl sharedManager].isWXSigninToken = [UIToolsControl dataAnalysis:responseObject[@"data"][@"token"]];
//
//            self->responseObjectDic = responseObject;
            [self detailDataAndPushVC:self->responseObjectDic];
        } else {
            NSString *str = [NSString stringWithFormat:@"%@", responseObject[@"msg"]];
            SVPHUDError(str);
        }
    } failurBlock:^(NSError *error) {
        SVPHUDError(NetErrorAlertText);
    }];
}

@end
